<?php
namespace app\api\controller\wanlshop;

use app\admin\model\video\Videocontents;
use app\api\model\wanlshop\UserVideoLook;
use app\common\controller\Api;
use addons\wanlshop\library\AliyunSdk\Video as Vod;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * WanlShop验证接口
 */
class Video extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    
    public function _initialize()
    {
        parent::_initialize();
		$this->model = new \app\api\model\wanlshop\Video;
    }

    /**
     * 获取视频上传地址和凭证
     *
     */
    public function getUploadProof($name)
    {
		$config = get_addon_config('wanlshop');
        $vod = new Vod($config['video']['regionId'], $config['video']['accessKeyId'], $config['video']['accessKeySecret']);
        $sts = $vod->createUploadVideo($name, $name, $config['video']['workflowId']);
		if(!$sts){
			$this->error(__('获取上传凭证失败！'));
		}
		$uploadAuth = json_decode(base64_decode($sts->UploadAuth));
		$uploadAddress = json_decode(base64_decode($sts->UploadAddress));
		$ossUrl = parse_url($uploadAddress->Endpoint)['scheme'] . '://' . $uploadAddress->Bucket .'.'.parse_url($uploadAddress->Endpoint)['host'];
		$policy = base64_encode('{"expiration":"'.$uploadAuth->ExpireUTCTime.'","conditions":[["content-length-range",0,1048576000]]}');
		$signature = base64_encode(hash_hmac('sha1', $policy, $uploadAuth->AccessKeySecret, true));
		$this->success('ok', [
			'ossUrl' => $ossUrl,
			'file' => 'file',
			'videoId' => $sts->VideoId,
			'formData' => [
				'OSSAccessKeyId' => $uploadAuth->AccessKeyId,
				'policy' => $policy,
				'key' => $uploadAddress->FileName,
				'x-oss-security-token' => $uploadAuth->SecurityToken,
				'success_action_status' => '200',
				'Signature' => $signature
			]
		]);
    }


    /**
     * 视频分类
     */
    public function tabs(){
        $model = new Videocontents();
        $data = $model->getTypeListTwo();
        $typeArr = [];
        $key = -1;
        foreach ($data as $k=>$v){
            $key +=1;
            $typeArr[$key]['id'] = $k;
            $typeArr[$key]['name'] = $v;
        }
        $this->success('ok', $typeArr);
    }

    /**
     *
     * 视频列表
     */
    public function videolist(){
        $model = new Videocontents();
        $type = input('type');
        $where['status'] = 1;
        if($type){
            $where['type'] = $type;
        }
       $data =  $model->where($where)->order('weigh desc')->paginate();
        $this->success('ok',$data);
    }


    /**
     * 详情
     */
    public function detail(){
        $where['video_contents_id'] = input('id');
        //查询是否能存在观影记录
        $lookModel = new UserVideoLook();
        $lookInfo = $lookModel->where(['user_id'=>$this->auth->id,'video_contents_id'=> $where['video_contents_id']])->order('updatetime desc')->find();
        if($lookInfo){
            $where['id'] = $lookInfo['video_id'];
        }
        $model = new \app\admin\model\video\Video();
        $videoInfo = $model->where($where)->order('weigh asc')->find();
        if(!$videoInfo){
            if(empty($where['id'])){
                $this->error('视频不存在');
            }
            unset($where['id']);
            $videoInfo = $model->where($where)->order('weigh asc')->find();
            if(!$videoInfo){
                $this->error('视频不存在');
            }
        }
        if($videoInfo['is_pay'] != 1){
            if(time() > $this->auth->video_end_time){
                $this->error('请联系管理员充值');
            }
        }
        $videoInfo->setInc('look');
        $lookAll = $model->where(['video_contents_id'=>$where['video_contents_id']])->sum('look');
        $contentsInfo = Videocontents::where(['id'=>$where['video_contents_id']])->find();
        $this->success('ok',['video_info'=>$videoInfo,'contents_info'=>$contentsInfo,'look_all'=>$lookAll]);
    }


    public function detailtest(){

        $url = 'https://happygomall.com/videos/index.m3u8';
        $this->success('ok',['video_info'=>['videoUrl'=>$url,'video_image'=>'https://happygoma.oss-cn-hongkong.aliyuncs.com/uploads/20250907/49845604e7e65997a54d3974bf016e9f.jpg'],'contents_info'=>[],'look_all'=>[]]);
    }

    /**
     * 获取所有集
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function episodes(){
        $where['video_contents_id'] = input('videoId');
        $where['status'] = 1;
        $model = new \app\admin\model\video\Video();
        $data = $model->where($where)->order('weigh asc')->select();
        $this->success('ok',$data);
    }

    /**
     * 观影记录
     */
    public function history(){
        $lookModel = new UserVideoLook();
        $episodeId = input('episodeId');
        $videoId   = input('videoId');
        $lookInfo = $lookModel->where(['user_id'=>$this->auth->id,'video_id'=>$episodeId,'video_contents_id'=>$videoId])->find();
        if($lookInfo){
            $lookInfo->updatetime = time();
            $lookInfo->save();
        }else{
            $lookModel->user_id = $this->auth->id;
            $lookModel->video_id = $episodeId;
            $lookModel->video_contents_id = $videoId;
            $lookModel->save();
        }
        $this->success('ok');
    }
}
